package com.lz.service.file;

import cn.hutool.core.io.FileUtil;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileVerifyUtil {

    public static String readFileContent(File file) {
        if (!file.exists()) {
            throw new RuntimeException("文件不存在：" + file.getAbsolutePath());
        }

        String fileName = file.getName().toLowerCase();

        if (fileName.endsWith(".txt")) {
            return readTXTString(file);
        } else if (fileName.endsWith(".pdf")) {
            return readPdf(file);
        } else if (fileName.endsWith(".docx")) {
            return readDocxFile(file);
        } else if (fileName.endsWith(".doc")) {
            return readDocxFile(file); // 假设你有实现
        } else {
            throw new RuntimeException("不支持的文件类型: " + fileName);
        }
    }

    // TXT
    public static String readTXTString(File file) {
        return FileUtil.readString(file, "utf-8");
    }

    // PDF
    public static String readPdf(File file) {
        try (PDDocument document = PDDocument.load(file)) {
            PDFTextStripper stripper = new PDFTextStripper();
            return stripper.getText(document);
        } catch (Exception e) {
            throw new RuntimeException("读取 PDF 文件失败: " + file.getAbsolutePath(), e);
        }
    }

    /**
     * 读取.doc文件
     */
    private static String readDocFile(File file) {
        try (FileInputStream fis = new FileInputStream(file);
             HWPFDocument document = new HWPFDocument(fis);
             WordExtractor extractor = new WordExtractor(document)) {
            return extractor.getText();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 读取.docx文件
     */
    private static String readDocxFile(File file) {
        try (FileInputStream fis = new FileInputStream(file);
             XWPFDocument document = new XWPFDocument(fis);
             XWPFWordExtractor extractor = new XWPFWordExtractor(document)) {
            return extractor.getText();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    // 测试入口
    public static void main(String[] args) {
        File file = new File("E:\\resource\\layout\\LZ-杂杂\\66.docx"); // .doc 文件
        System.out.println(readFileContent(file));
    }
}
